package com.product.exception;

import com.common.exception.BizCodeEnum;
import com.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 */
//@Slf4j
//@RestControllerAdvice(basePackages = "com.product.controller")
public class ExceptionControllerAdivice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    private R handleVaildException(MethodArgumentNotValidException e){
//        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errprMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            errprMap.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",errprMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(){
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
